import 'package:flutter/material.dart';
import 'package:audioplayers/audioplayers.dart';
import '../models/word_card.dart';
import '../models/word_book.dart';
import '../data/word_book_service.dart';
import '../widgets/word_card_widget.dart';
import 'dart:async';

class SpeedReadingPage extends StatefulWidget {
  final WordBook wordBook;
  final List<WordCard> words;

  const SpeedReadingPage({
    Key? key,
    required this.wordBook,
    required this.words,
  }) : super(key: key);

  @override
  _SpeedReadingPageState createState() => _SpeedReadingPageState();
}

class _SpeedReadingPageState extends State<SpeedReadingPage> {
  final AudioPlayer _audioPlayer = AudioPlayer();
  int _currentIndex = 0;
  bool _isDragging = false;
  double _dragOffset = 0.0;
  bool _showDetails = true; // 速读模式直接显示单词详情

  @override
  void initState() {
    super.initState();
    if (widget.words.isNotEmpty) {
      _playWordAudio(widget.words[_currentIndex]);
    }
  }

  @override
  void dispose() {
    _audioPlayer.dispose();
    super.dispose();
  }

  void _playWordAudio(WordCard word) {
    _audioPlayer.play(UrlSource('https://ali.bczcdn.com/r/${word.wordAudio}'));
  }

  void _onRemembered() async {
    if (_currentIndex >= widget.words.length) return;
    
    final WordCard word = widget.words[_currentIndex];
    
    // 将单词从新词词库移动到复习词库
    await WordBookService.addWordToReview(widget.wordBook.id, word);
    
    _moveToNextWord();
  }

  void _onForgotten() async {
    if (_currentIndex >= widget.words.length) return;
    
    final WordCard word = widget.words[_currentIndex];
    await WordBookService.addWordToNew(widget.wordBook.id, word);
    
    _moveToNextWord();
  }

  void _moveToNextWord() {
    setState(() {
      _currentIndex++;
      _dragOffset = 0.0;
    });
    
    if (_currentIndex < widget.words.length) {
      _playWordAudio(widget.words[_currentIndex]);
    } else {
      // 所有单词都已学习完毕
      _showCompletionDialog();
    }
  }

  void _showCompletionDialog() {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => AlertDialog(
        title: Text('恭喜！'),
        content: Text('您已完成所有单词的学习。'),
        actions: [
          TextButton(
            onPressed: () {
              Navigator.of(context).pop(); // 关闭对话框
              Navigator.of(context).pop(); // 返回上一页
            },
            child: Text('返回'),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    if (widget.words.isEmpty || _currentIndex >= widget.words.length) {
      return Scaffold(
        appBar: AppBar(
          title: Text('速读模式'),
        ),
        body: Center(
          child: Text('没有更多单词了'),
        ),
      );
    }

    final WordCard currentWord = widget.words[_currentIndex];
    final screenWidth = MediaQuery.of(context).size.width;
    final maxDragDistance = screenWidth * 0.4;
    
    // 计算卡片旋转角度和偏移
    final double rotationAngle = _dragOffset / 500;
    final double cardOffset = _dragOffset;
    
    // 计算背景颜色透明度
    final double rememberedOpacity = _dragOffset > 0 ? _dragOffset.abs() / maxDragDistance : 0.0;
    final double forgottenOpacity = _dragOffset < 0 ? _dragOffset.abs() / maxDragDistance : 0.0;

    // 底部操作按钮
    final Widget actionButtons = Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
      children: [
        // 记住按钮（红心）
        ElevatedButton(
          onPressed: _onRemembered,
          style: ElevatedButton.styleFrom(
            shape: CircleBorder(),
            padding: EdgeInsets.all(20),
            backgroundColor: Colors.red,
          ),
          child: Icon(Icons.favorite, color: Colors.white),
        ),
        
        // 遗忘按钮（黑叉）
        ElevatedButton(
          onPressed: _onForgotten,
          style: ElevatedButton.styleFrom(
            shape: CircleBorder(),
            padding: EdgeInsets.all(20),
            backgroundColor: Colors.black,
          ),
          child: Icon(Icons.close, color: Colors.white),
        ),
      ],
    );

    return Scaffold(
      appBar: AppBar(
        title: Text('速读模式'),
      ),
      body: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topLeft,
            end: Alignment.bottomRight,
            colors: [
              Colors.blue.withOpacity(0.3),
              Colors.purple.withOpacity(0.3),
            ],
          ),
        ),
        child: Stack(
          children: [
            // 记住背景指示
            Positioned.fill(
              child: Container(
                color: Colors.green.withOpacity(rememberedOpacity * 0.5),
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.only(left: 40),
                child: Icon(
                  Icons.favorite,
                  color: Colors.white,
                  size: 80 * rememberedOpacity,
                ),
              ),
            ),
            
            // 遗忘背景指示
            Positioned.fill(
              child: Container(
                color: Colors.red.withOpacity(forgottenOpacity * 0.5),
                alignment: Alignment.centerRight,
                padding: EdgeInsets.only(right: 40),
                child: Icon(
                  Icons.close,
                  color: Colors.white,
                  size: 80 * forgottenOpacity,
                ),
              ),
            ),
            
            // 单词卡片
            Center(
              child: GestureDetector(
                onHorizontalDragStart: (details) {
                  setState(() {
                    _isDragging = true;
                  });
                },
                onHorizontalDragUpdate: (details) {
                  setState(() {
                    _dragOffset += details.delta.dx;
                  });
                },
                onHorizontalDragEnd: (details) {
                  if (_dragOffset.abs() > maxDragDistance) {
                    if (_dragOffset > 0) {
                      _onRemembered();
                    } else {
                      _onForgotten();
                    }
                  } else {
                    setState(() {
                      _dragOffset = 0.0;
                      _isDragging = false;
                    });
                  }
                },
                child: Transform.rotate(
                  angle: rotationAngle,
                  child: Transform.translate(
                    offset: Offset(cardOffset, 0),
                    child: Container(
                      width: MediaQuery.of(context).size.width * 0.85,
                      height: MediaQuery.of(context).size.height * 0.7,
                      child: WordCardWidget(
                        wordCard: currentWord,
                        showDetails: _showDetails,
                        onTap: () {
                          _playWordAudio(currentWord);
                        },
                        bottomActions: actionButtons,
                      ),
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
} 